<template>
  <view class="product w100 h100 flex-col" :style="{ '--theme': themeColor }">
    <nav-bar :title="type == 'add' ? '添加商品' : '编辑商品'" />
    <view class="page flex1 flex-col">
      <view class="content flex-col flex1">
        <u--form :model="form" :rules="rules" ref="form1">
          <view class="classify">
            <view class="top flex flexAIC">
              <view class="left">商品分类</view>
              <view class="right flex1 flexAIC">
                <u-form-item
                  prop="categoryId"
                  labelWidth="0rpx"
                  @click="showChooseClass = true"
                  class="flex1"
                >
                  <u--input
                    v-model="classOptions[form.categoryId]"
                    disabled
                    disabledColor="#ffffff"
                    placeholder="请选择商品分类"
                    border="none"
                  />
                  <u-icon slot="right" name="arrow-down" />
                </u-form-item>
              </view>
            </view>
            <view class="msg">
              <view class="title">商品信息</view>
              <view class="name marginBottom-30">
                <view class="title marginBottom-30">商品名称</view>
                <view>
                  <u-form-item prop="title" labelWidth="0rpx">
                    <view class="show-count">
                      <u--input
                        v-model="form.title"
                        maxlength="60"
                        :showWordLimit="true"
                        placeholder="请输入商品名称"
                        border="none"
                      />
                      <view class="num">{{ form.title.length }} / 60</view>
                    </view>
                  </u-form-item>
                </view>
              </view>
              <view class="imgs">
                <view class="title marginBottom-23">商品主图</view>
                <view class="tip"
                  >只能上传jpg/png文件,且每张不超过1mb，最多可上传10张</view
                >
                <view class="list">
                  <u-upload
                    :fileList="fileList1"
                    @afterRead="afterRead"
                    @delete="deletePic"
                    name="1"
                    multiple
                    :maxCount="10"
                    maxSize="1048576"
                    uploadIcon="plus"
                  />
                </view>
              </view>
              <view class="spec">
                <view class="flex-btw flexAIC">
                  <view class="title">规格</view>
                  <view class="spec-right flex1 flexAIC">
                    <u-form-item
                      prop="specList"
                      labelWidth="0rpx"
                      @click="toSetSpec()"
                      class="flex1"
                    >
                      <u--input
                        v-model="specLength"
                        disabled
                        disabledColor="#ffffff"
                        placeholder="请设置规格"
                        border="none"
                      />
                      <u-icon slot="right" name="arrow-right" />
                    </u-form-item>
                  </view>
                </view>
                <view class="flex-btw">
                  <view class="title">规格明细</view>
                  <view class="flex1 flexAIC flex">
                    <view
                      :class="[
                        'flex1',
                        'flex',
                        'flex-end',
                        form.skuList.length > 0 ? '' : 'placeholder',
                      ]"
                      >共{{ form.skuList.length }}项</view
                    >
                    <view class="iconfont icon-xiangyoujiantou"></view>
                  </view>
                </view>
              </view>
              <view class="remark">
                <view class="title marginBottom-30">商品描述</view>
                <view>
                  <u--textarea
                    v-model="form.description"
                    placeholder="请输入内容"
                    count
                    maxlength="200"
                  />
                </view>
              </view>
              <view class="hint marginTop-25">
                提示：保存后分店不显示商品，商品上架后才显示在分店；
              </view>
            </view>
          </view>
        </u--form>
        <view class="bottom">
          <view class="btns flex flex-btw">
            <view class="center" @click="save()">保存</view>
            <view class="center" @click="save('up')">保存并上架</view>
          </view>
        </view>
      </view>
    </view>
    <classify-pop
      :visible.sync="showChooseClass"
      :categoryId="form.categoryId"
      @chooseClass="chooseClass"
    />
  </view>
</template>

<script>
import classifyPop from "@/components/pageComponents/sp-product/classify-pop";
import {
  getProductDetail,
  searchClass,
  addProduct,
  updateProduct,
} from "@/service/api/sp-product/index";
import { mapState, mapActions } from "vuex";

export default {
  data() {
    return {
      rules: {
        categoryId: [
          {
            type: "number",
            required: true,
            message: "请选择商品分类",
            trigger: ["blur", "change"],
          },
        ],
        title: [
          {
            type: "string",
            required: true,
            message: "请输入商品名称",
            trigger: ["blur", "change"],
          },
          {
            type: "string",
            required: true,
            max: 60,
            message: "超出最大可输入内容",
            trigger: ["blur", "change"],
          },
        ],
        specList: [
          {
            type: "array",
            min: 1,
            required: true,
            message: "请设置规格",
            trigger: ["blur", "change"],
          },
        ],
      },
      showChooseClass: false,
      fileList1: [],
      value2: "",
      value: "",
      type: "add",
      form: {
        goodsType: 100, // 商品类型100: 实物商品(物流), 200: 券包(虚拟商品), 300: 同城配送/自提
        // 关联物品
        goodsItems: [],
        couponVerRadio: "COUPON2",
        categoryId: "", // 商品类目
        categoryIds: [], // 商品类目
        brandId: 0, // 商品品牌
        goodsNo: "", // 商品编码
        barCode: "", // 商品条码
        goodsUnit: "件", // 商品单位
        title: "", // 商品标题
        subTitle: "", // 商品子标题
        description: "", // 商品描述
        specList: [], // 规格信息
        // 规格信息
        skuList: [],
        // 参数 服务信息
        goodsExt: {
          paramList: [],
          supportList: [],
        },
        // 限制规则
        goodsRule: {
          canUseDiscount: false,
          limited: false,
          memberType: 0, // 0:所有顾客, 1:会员, 2:仅指定会员
          cardIdList: [],
          limitNum: "",
          payChannels: ["1"],
        },
        // 预售
        presell: false,
        goodsPresell: {
          type: "FULL",
          depositType: 0,
          depositQuota: null,
          limitTime: true,
          preDate: null,
          beginTime: null,
          endTime: null,
          afterTheEnd: 0,
          remainingBeginTime: null,
          remainingEndTime: null,
          defaultRule: 0,
          defaultFineType: 0,
          defaultFine: null,
          prepareType: 1,
          prepareTime: null,
          prepareUnit: "DAYS",
          prepareBeginTime: null,
          cancelRule: 0,
          cancelFreeTime: null,
          cancelChargeType: 0,
          cancelCharge: null,
          remark: null,
        },
        // 预览信息
        displayInfo: {
          detailImages: [],
          imageList: [],
        },
        goodsDelivery: {
          canExpress: true,
          expressPrepare: null,
          expressPrepareUnit: "HOURS",
          canLocalDelivery: true,
          localPrepare: null,
          localPrepareUnit: "HOURS",
          canSelfPickup: true,
          selfPickupPrepare: null,
          selfPickupPrepareUnit: "HOURS",
        },
        goodsBargains: [], // 加购
        specInputValueExcl: null, // specInput临时绑定值
      },
      classOptions: "",
      goodsId: "",
    };
  },
  components: {
    classifyPop,
  },
  computed: {
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
    specLength() {
      return this.form.specList.length > 0
        ? `共${this.form.specList.length}项`
        : "请设置规格";
    },
    ...mapState("sp-common/auth", ["pubUserInfo", "token"]),
    ...mapState("sp-product/index", ["classifyList"]),
    ...mapState("sp-product/index", {
      vxSkus: "skuList",
      vxspecList: "specList",
      vxstoreList: "storeList",
    }),
  },
  created() {},
  async mounted() {
    this.$refs.form1.setRules(this.rules);
    if (this?.$Route?.query?.goodsId) {
      let { type } = this?.$Route?.query;
      this.type = type;
      this.goodsId = this?.$Route?.query?.goodsId;
      await this.getProductDetail();
    }
    await this.searchClass();
    await this.initSkus();
  },
  watch: {
    classifyList(val) {
      this.searchClass();
    },
  },
  methods: {
    ...mapActions("sp-product/index", [
      "setSkuList",
      "setSpecList",
      "setStoreList",
    ]),
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: `${process.env.VUE_APP_BASE_URL}/business_admin/upload`,
          filePath: url,
          header: {
            "X-BUSINESS-TOKEN": this.token,
          },
          name: "file",
          success: (res) => {
            setTimeout(() => {
              let result = JSON.parse(res.data).data;
              resolve(result.path);
            }, 1000);
          },
        });
      });
    },
    chooseClass(data) {
      let { categoryId } = data;
      this.form.categoryId = String(categoryId);
      this.$refs.form1.validateField("categoryId");
    },
    getProductDetail() {
      return new Promise((resolve, reject) => {
        let {
          pubUserInfo: { mainShopStatus },
          goodsId,
          type,
        } = this;
        getProductDetail({
          mainShopStatus,
          goodsId,
          copy: type === "copy" ? true : false,
        }).then((res) => {
          this.form = res;
          if (res?.displayInfo?.imageList.length > 0) {
            res?.displayInfo?.imageList.forEach((item) => {
              item = process.env.VUE_APP_BASE_FileUrl + item;
              this.fileList1.push({ url: item });
            });
          }
          resolve();
        });
      });
    },
    searchClass() {
      let classPar = { "": "" };
      this.classifyList.forEach((item) => {
        classPar[item.id] = item.title;
      });
      this.classOptions = classPar;
    },
    toSetSpec() {
      this.$myTool.jumpPage("specSet", { type: "edit" });
    },
    initSkus() {
      let {
        form: { skuList, specList, pubStoreSkuLiVOList = [] },
      } = this;
      if (pubStoreSkuLiVOList?.length > 0) {
        pubStoreSkuLiVOList.forEach((ele) => {
          if (ele.skus?.length > 0) {
            ele.skus.forEach((element) => {
              element.price = element.price / 100;
            });
          }
        });
      }
      this.setSkuList(skuList);
      this.setSpecList(specList);
      this.setStoreList(pubStoreSkuLiVOList);
    },

    save(option) {
      let {
        form,
        fileList1,
        pubUserInfo: { mainShopStatus },
        type,
        goodsId,
      } = this;
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2]; //上一页页面实例
      this.$refs.form1.validate().then((res) => {
        if (res) {
          let imgList = [];
          if (fileList1.length > 0) {
            fileList1.forEach((item) => {
              let l = item.url.replace(process.env.VUE_APP_BASE_FileUrl, "");
              imgList.push(l);
            });
          }
          if (imgList.length <= 0) {
            uni.showToast({
              title: "请上传商品图片",
              icon: "none",
            });
          }
          if (form.skuList.length <= 0) {
            uni.showToast({
              title: "请设置规格",
              icon: "none",
            });
          }
          form.displayInfo.imageList = imgList;
          form.mainShopStatus = mainShopStatus;
          form?.pubStoreSkuLiVOList.map((ele) => {
            if (ele?.skus?.length > 0) {
              ele.skus.map((sku) => {
                const price = sku.price;
                sku.price = price * 100;
              });
            }
          });

          if (form?.skuList?.length > 0) {
            form?.skuList.map((ele) => {
              type != "edit" && type != "copy" ? (ele.price *= 100) : "";
              option === "up" ? (ele.status = 1) : "";
            });
          }
          if (type === "edit") {
            form.goodsId = goodsId;
            updateProduct(form).then((res) => {
              uni.showToast({
                title: "保存商品成功",
                icon: "none",
              });
              prevPage.$vm.getProduct();
              uni.navigateBack({
                delta: 1,
              });
            });
          } else {
            addProduct(form).then((res) => {
              uni.showToast({
                title: "新增商品成功",
                icon: "none",
              });
              prevPage.$vm.getProduct();
              uni.navigateBack({
                delta: 1,
              });
            });
          }
        }
      });
    },
    saveSpec() {
      this.form.skuList = this.vxSkus;
      this.form.specList = this.vxspecList;
      this.form.pubStoreSkuLiVOList = this.vxstoreList;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../css/add-product.scss";
</style>
